import base64
import json


from json import JSONDecodeError

from locust import task, FastHttpUser, constant, tag, run_single_user, events

import requests


index_cookie = 2000
requests.packages.urllib3.disable_warnings()

def get_cookie():
    global index_cookie
    index_cookie += 1
    l = []
    with open('../cookie.txt', mode='r', encoding='utf8') as f:
        for account in f:
            l.append(account.strip())
        return str(l[index_cookie])


def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')


def decode64_str(data):
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str


@events.test_start.add_listener
def on_test_start(environment, **kwargs):

    print("A new test is starting")


@events.test_stop.add_listener
def on_test_stop(environment, **kwargs):
    print("stopingtest")

class FeedBack(FastHttpUser):
    host = "https://www.retone-hearing.fit"
    wait_time = constant(300)
    # abstract = True
    cookie = get_cookie()
    default_headers =  {"Content-Type": "application/json"}
    header = default_headers
    # def on_start(self):
    #     numbers_of_user = True
    #     if numbers_of_user == True:
    #         self.header = {"Cookie": f"hearingaid_user={get_cookie()}",
    #                        "Content-Type": "application/json"}
    #     else:
    #         self.header = {"Cookie": f"hearingaid_user={self.cookie}",
    #                        "Content-Type": "application/json"}
    num = 1
    @task
    @tag("feedback")
    def user_feedback(self):
        # print(self.header['Cookie'])
        url = '/platformRetoneFit/api/feedback/needAppUserAuth/responseEncode/requestDecode/addFeedback'
        data = {"feedbackContent": "FastHttpUser_test+{self.host}+{index_cookie}"}
        with self.rest('post', url, data=enconde_bs64(data), headers=self.header) as resp:
            try:
                if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()['description'] != None):
                    resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
                else:
                    # print(resp.json())
                    resp.success()
            except JSONDecodeError:
                resp.failure("Response could not be decoded as JSON")
            except KeyError:
                resp.failure("Response did not contain expected key 'data'")


if __name__ == '__main__':
    run_single_user(FeedBack)